package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.plaf.basic.BasicSliderUI.ActionScroller;

import validator.ServiceValidator;

import model.dao.registerOrder.DeviceDAOImpl;
import model.dao.registerOrder.ServiceActionDAOImpl;
import model.dao.registerOrder.ServiceDeviceDAOImpl;
import model.dao.registerOrder.ServiceOrderDAOImpl;
import model.dao.registerOrder.ServiceOrderImpl;
import model.dao.registerOrder.ServicePartDAOImpl;
import model.dao.registerOrder.ServiceRequestDAOImpl;
import model.dao.registerOrder.insertOrderReqImpl;
import model.service.Customer;
import model.service.Device;
import model.service.Employee;
import model.service.ServiceAction;
import model.service.ServiceActionStatusType;
import model.service.ServiceDevice;
import model.service.ServiceOrder;
import model.service.ServicePart;
import model.service.ServiceRequest;
import model.service.ServiceRequestStatusType;
import model.service.ServiceType;
import model.service.SoStatusType;

public class ServiceController {
	private static final int ArrayList = 0;
	HttpServletRequest req;
	HttpServletResponse res;
	ServletContext servletContext;
	HttpSession session;
	
	public ServiceController(HttpServletRequest req, HttpServletResponse res,
			ServletContext servletContext, HttpSession session) throws ServletException, IOException {
		this.req = req;
		this.res = res;
		this.servletContext = servletContext;
		this.session = session;
		
		if (req.getParameter("task") != null && req.getParameter("task").equalsIgnoreCase("service_request"))
			service_request();
		else if (req.getParameter("task") != null && req.getParameter("task").equalsIgnoreCase("order_request"))
			order_request();
		else if (req.getParameter("task") != null && req.getParameter("task").equalsIgnoreCase("service_request_list"))
			service_request_list();
		else if (req.getParameter("task") != null && req.getParameter("task").equalsIgnoreCase("delete_request"))
			delete_request();
		else if (req.getParameter("task") != null && req.getParameter("task").equalsIgnoreCase("service_order_list"))
			service_order_list();
		return;

	}
	
	public void service_request() throws ServletException, IOException {
		
		HashMap<String, String> hashmap = new HashMap<String, String>();
		ServiceValidator sv = new ServiceValidator();
		
		if (req.getParameter("save_request") != null || req.getParameter("insert_order") != null) {
			hashmap = sv.validateOrderRequest(req.getParameter("user_id"), req.getParameter("customer_desc"), req.getParameter("employee_desc"));
			if (hashmap.size() == 0) {
				insertOrderReqImpl db = new insertOrderReqImpl();
				ServiceRequest sr = new ServiceRequest();
				sr.setCustomer(new Customer(Integer.parseInt(req.getParameter("user_id").toString())));
				sr.setCreatedBy(new Employee(Integer.parseInt(session.getAttribute("userId").toString())));
				sr.setCustomerDescription(req.getParameter("customer_desc"));
				sr.setEmployeeDescription(req.getParameter("employee_desc"));
				sr.setServiceRequestStatusType(new ServiceRequestStatusType(1));
				int service_request_id = db.saveOrderRequest(sr);
				if (req.getParameter("insert_order") != null) {
					res.sendRedirect("/r56_remonditeenus/s?action=service&task=order_request&service_request_id="+service_request_id);
					return;
				}
			}
		}
		
		req.setAttribute ("errors", hashmap);
		servletContext.getRequestDispatcher("/service_request.jsp").forward(req, res);
		return;
	}
	
	public void order_request() throws ServletException, IOException {
		HashMap<String, String> hashmap = new HashMap<String, String>();
		ServiceValidator sv = new ServiceValidator();
		int id = 0;
		ServiceOrder so = new ServiceOrder();
		ServiceOrderImpl dao;
		ServiceAction action = new ServiceAction();
		ServiceAction action_saved = new ServiceAction();
		ServiceActionDAOImpl dao_action = new ServiceActionDAOImpl();
		List<ServiceAction> actions = new ArrayList<ServiceAction>();
		ServicePart servicePart = new ServicePart(); 
		ServicePartDAOImpl part_dao = new ServicePartDAOImpl();
		ServicePart part_saved = new ServicePart();
		Device device = new Device();
		List<ServiceDevice> devices = new ArrayList<ServiceDevice>(); 
		ServiceDeviceDAOImpl device_dao = new ServiceDeviceDAOImpl();
		DeviceDAOImpl device_specific_dao = new DeviceDAOImpl();
		ServiceDevice serviceDevice = null;
		
		if (req.getParameter("service_order_id") != null) {
			dao = new ServiceOrderImpl();
			id = Integer.parseInt(req.getParameter("service_order_id").toString());
			so = dao.getServiceOrderById(id);
			actions = dao_action.getServiceActions(id);
			if (actions.size() > 0) {
				for (ServiceAction a : actions) {
					action_saved = a;
					break;
				}
			}
			List<ServicePart> parts = part_dao.getServiceParts(id);
			if (parts.size() > 0) {
				for (ServicePart sp : parts) {
					part_saved = sp;
					break;
				}
			}

			devices = device_dao.getServiceDevicesByServiceOrder(id);
			if (devices.size() > 0) {
				for (ServiceDevice d : devices) {
					device = device_specific_dao.getDeviceById(d.getDevice().getDevice());
					serviceDevice = d;
					break;
				}
			}
		}

		if (req.getParameter("save_order") != null || req.getParameter("generate_invoice") != null) {
			dao = new ServiceOrderImpl();
			so = new ServiceOrder();
			Employee emp = new Employee();
			emp.setEmployee(Integer.parseInt(session.getAttribute("userId").toString()));
			so.setCreatedBy(emp);
			so.setServiceRequest(new ServiceRequest(Integer.parseInt(req.getParameter("service_request_id").toString())));
			so.setNote(req.getParameter("note").toString());
			so.setSoStatusType(new SoStatusType(Integer.parseInt(req.getParameter("so_status_type").toString())));
			if (req.getParameter("service_order_id") != null) {
				so.setServiceOrder(Integer.parseInt(req.getParameter("service_order_id").toString()));
				dao.updateServiceOrder(so);
				id = so.getServiceOrder();
			}
			else {
				id = dao.insertServiceOrder(so);	
			}
			
			if (req.getParameter("note") != null && req.getParameter("device_id") != null) {
				
				//Service type
				int service_type = 0;
				String service_type_string = req.getParameter("service_type").toString();
				if (!service_type_string.equalsIgnoreCase("")) {
					service_type = Integer.parseInt(service_type_string);
				}
				action.setServiceType(new ServiceType(service_type));
				
				//Device id
				int device_id = 0;
				String device_id_string = req.getParameter("device_id").toString();
				if (!device_id_string.equalsIgnoreCase("")) {
					device_id = Integer.parseInt(device_id_string);
				}
				action.setServiceDevice(new ServiceDevice(device_id));
				
				//number of work hours
				float hours = 0;
				String hours_string = req.getParameter("hours").toString();
				if (!hours_string.equalsIgnoreCase("")) {
					hours = Float.parseFloat(hours_string);
				}

				action.setServiceAmount(hours);

				//price of one hour
				float hour_price = 0;
				String hour_price_string = req.getParameter("hour_price").toString();
				if (!hour_price_string.equalsIgnoreCase("")) {
					hour_price = Float.parseFloat(hour_price_string);
				}
				action.setPrice(hour_price);
				
				action.setServiceActionStatusType(new ServiceActionStatusType(1));
				action.setServiceOrder(new ServiceOrder(id));
				action.setActionDescription(req.getParameter("note"));
				action.setCreatedBy(new Employee(Integer.parseInt(session.getAttribute("userId").toString())));
				if (action_saved.equals(null)) {
					dao_action.insertServiceAction(action);	
				}
				else {
					action.setServiceAction(action_saved.getServiceAction());
					dao_action.updateServiceAction(action);
				}
				
				servicePart.setServiceOrder(new ServiceOrder(id));
				servicePart.setServiceDevice(new ServiceDevice(device_id));
				
				String part_name = req.getParameter("part_name").toString();
				servicePart.setPartName(part_name);
				
				int part_amount = 0;
				String part_amount_string = req.getParameter("amount").toString();
				if (!part_amount_string.equalsIgnoreCase("")) {
					part_amount = Integer.parseInt(part_amount_string);
				}
				servicePart.setPartCount(part_amount);

				float part_price = 0;
				String part_price_string = req.getParameter("unit_price").toString();
				if (!part_price_string.equalsIgnoreCase("")) {
					part_price = Float.parseFloat(part_price_string);
				}
				servicePart.setPartPrice(part_price);
				
				servicePart.setCreatedBy(new Employee(Integer.parseInt(session.getAttribute("userId").toString())));

				servicePart.setSerialNo("0");
				
				part_dao = new ServicePartDAOImpl();
				if (part_saved == null) {
					part_dao.insertServicePart(servicePart);
				}
				else {
					servicePart.setServicePart(part_saved.getServicePart());
					part_dao.updateServicePart(servicePart);
				}
				
				ServiceDevice sd = new ServiceDevice();
				sd.setDevice(new Device(device_id));
				sd.setServiceOrder(new ServiceOrder(id));
				
				if (serviceDevice == null && device_id > 0) {
					sd.setDevice(new Device(device_id));
					sd.setServiceOrder(new ServiceOrder(id));
					device_dao.insertServiceDevice(sd);
				}
				else if (serviceDevice != null && device_id > 0) {
					sd.setDevice(new Device(device_id));
					sd.setServiceOrder(new ServiceOrder(id));
					sd.setServiceDevice(serviceDevice.getServiceDevice());
					device_dao.updateServicedevice(sd);
				}
				
			}

			res.sendRedirect("/r56_remonditeenus/s?action=service&task=order_request&service_request_id="+req.getParameter("service_request_id")+"&service_order_id="+id);
			return;
		}
		req.setAttribute("result", so);
		req.setAttribute("errors", hashmap);
		req.setAttribute("action", action_saved);
		req.setAttribute("part", part_saved);
		req.setAttribute("device", device);
		servletContext.getRequestDispatcher("/order_request.jsp").forward(req, res);
		return;
	}
	
	public void service_request_list() throws ServletException, IOException
	{
		ArrayList<ServiceRequest> request = new ServiceRequestDAOImpl().getServiceRequest();
		req.setAttribute("requests", request);
		servletContext.getRequestDispatcher("/service_request_list.jsp").forward(req, res);
		return;
	}
	
	public void service_order_list() throws ServletException, IOException
	{
		//List<ServiceOrder> orers = new ServiceOrderDAOImpl().getPersonServiceOrders(Integer.parseInt(session.getAttribute("userId").toString()));
		ArrayList<ServiceRequest> request = new ServiceRequestDAOImpl().getServiceRequest(Integer.parseInt(session.getAttribute("customer_id").toString()));
		req.setAttribute("requests", request);
		servletContext.getRequestDispatcher("/service_order_list.jsp").forward(req, res);
		return;
	}
	
	public void delete_request() throws ServletException, IOException
	{
		if (req.getParameter("id") != null) {
			int id = Integer.parseInt(req.getParameter("id").toString());
			new ServiceRequestDAOImpl().deleteServiceRequest(id);
		}
	}

}
